﻿using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Trentacular.SharePoint.Deployment.Model;
using Trentacular.SharePoint.Deployment.Util;

namespace Trentacular.SharePoint.Deployment.Data.Proxy
{
    public class WebApplicationSitesLazyInitializer : BaseDomainListLazyInitializer<WebApplication, Site>
    {
        protected override object InitializeTarget()
        {
            var spFarm = SPFarm.Local;
            var service = spFarm.Services.GetValue<SPWebService>("");
            var spWebApp = service.WebApplications[Owner.Id];

            return spWebApp.Sites.Cast<SPSite>()
                .Select(s => CreateSite(s))
                .ToVirtualList();
        }

        private Site CreateSite(SPSite s)
        {
            using (s)
            {
                using (var rootWeb = s.RootWeb)
                {
                    var site = new Site
                    {
                        Id = s.ID,
                        Name = rootWeb.Name,
                        Url = rootWeb.Url,
                        WebApplication = Owner
                    };

                    site.Webs = Data.CreateProxiedList<Web>(
                        new SiteWebsLazyInitializer { Owner = site }
                        );

                    site.Features = Data.CreateProxiedList<SiteFeature>(
                        new SiteFeaturesLazyInitializer { Owner = site }
                        );

                    return site;
                }
            }
        }
    }
}
